import React from "react";
import { SettingDrawer, PageLoading } from "@ant-design/pro-layout";
import { history } from "umi";
import RightContent from "@/components/RightContent";
import Footer from "@/components/Footer";
import defaultSettings from "../config/defaultSettings";
import routes from "../config/routes";
import moment from "moment";

const isDev = process.env.NODE_ENV === "development";
const loginPath = "/admin/login";
/** 获取用户信息比较慢的时候会展示一个 loading */

export const initialStateConfig = {
  loading: <PageLoading />,
};
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

export async function getInitialState() {
  const fetchUserInfo = async () => {
    try {
      // const msg = await queryCurrentUser();
      const userInfo = localStorage.getItem("adminInfo");
      return JSON.parse(userInfo);
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  // 如果不是登录页，则调用fetchUserInfo获取用户信息。
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
      routes,
    };
  } else {
    // 是登录页，这里由于是从本地获取，没有从服务端获取，则和不是登录页走一样的逻辑
    const currentUser = await fetchUserInfo();
    return {
      currentUser,
      fetchUserInfo,
      settings: defaultSettings,
      routes,
    };
  }
}

export const layout = ({ initialState, setInitialState }) => {
  console.log("initialState", initialState);

  // 如果当前路由在登录页且已经登录了，则直接跳转到首页
  if (initialState.currentUser && history.location.pathname === loginPath) {
    history.push("/");
  }

  // ProLayout 支持的api https://procomponents.ant.design/components/layout
  return {
    ...initialState?.settings,
    onMenuHeaderClick: () => {
      const permissionCodes = initialState?.currentUser?.permissionCodes;
      if (permissionCodes?.length) {
        const first = permissionCodes[0]; // RATIFY_PAGE
        const authRoutes = routes.filter((item) => item.access === first);
        const route = authRoutes.slice(-1)[0];
        history.push(route.path);
      }
    },
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // waterMarkProps: {
    //   gapX: 100,
    //   gapY: 100,
    //   zIndex: 100,
    //   width:
    //     initialState?.currentUser?.name?.length <= 6
    //       ? 200
    //       : initialState?.currentUser?.name?.length * 30,
    //   rotate: -6,
    //   fontSize: 13,
    //   content: `${initialState?.currentUser?.name} ${moment().format(
    //     "YYYY-MM-DD HH:mm:ss"
    //   )}`,
    // },
    // footerRender: () => <Footer />,
    onPageChange: (value) => {
      const { location } = history; // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,

    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {/* {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({ ...preInitialState, settings }));
              }}
            />
          )} */}
        </>
      );
    },
  };
};
